// 设置侧边栏默认打开
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });

// 创建右键菜单
chrome.runtime.onInstalled.addListener(() => {
    chrome.contextMenus.create({
        id: 'translateSelection',
        title: '翻译选中文本',
        contexts: ['selection']
    });

    chrome.contextMenus.create({
        id: 'summarizePage',
        title: '总结当前页面',
        contexts: ['page']
    });
});

// 处理选中文本
async function handleSelectedText(text) {
    // 等待侧边栏加载完成
    const sidePanelPort = chrome.runtime.connect({ name: 'sidePanel' });
    
    // 延迟发送消息，确保侧边栏已加载
    setTimeout(() => {
        chrome.runtime.sendMessage({
            type: 'setSelectedText',
            text: text
        });
    }, 500);
}

// 监听扩展图标点击事件
chrome.action.onClicked.addListener(async (tab) => {
    try {
        const [{ result }] = await chrome.scripting.executeScript({
            target: { tabId: tab.id },
            function: () => window.getSelection().toString()
        });
        
        if (result) {
            handleSelectedText(result);
        }
    } catch (error) {
        console.error('获取选中文本失败:', error);
    }
});

// 处理右键菜单点击事件
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
    if (info.menuItemId === 'translateSelection' && info.selectionText) {
        // 先打开侧边栏
        await chrome.sidePanel.open({ windowId: tab.windowId });
        // 处理选中的文本
        handleSelectedText(info.selectionText);
    } else if (info.menuItemId === 'summarizePage') {
        // 先打开侧边栏
        await chrome.sidePanel.open({ windowId: tab.windowId });
        // 延迟发送消息
        setTimeout(() => {
            chrome.runtime.sendMessage({
                type: 'summarizePage'
            });
        }, 500);
    }
}); 